﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Assignment
{
    public partial class SubcommitteeGroupsControl : UserControl
    {
        private readonly Business.Business _business;
        private List<Group> _groups;
        private List<Lecturer> _lecturers;

        public SubcommitteeGroupsControl()
        {
            InitializeComponent();
            _business = Main.Main.Instance.IgmBusiness;
        }

        private void SubcommitteeGroupsControlLoad(object sender, EventArgs e)
        {
            LoadMajor();
            LoadKindIntern();   
            LoadCondition(1,1);
            LoadSubcommittee();
            Dock = DockStyle.Top;
        }

        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }

        private void LoadKindIntern()
        {
            cboKindInterns.DataSource = _business.GetListKindIntern();
            cboKindInterns.DisplayMember = PropertiesConstants.Name;
            cboKindInterns.ValueMember = PropertiesConstants.Id;
        }

        private void LoadLecturer()
        {
            cboLecturers.DataSource = _business.GetListLecturerByMajorId(Convert.ToInt32(((Major)cboMajors.SelectedItem).Id));
            cboLecturers.DisplayMember = PropertiesConstants.Name;
            cboLecturers.ValueMember = PropertiesConstants.Id;
        }

        private void LoadGroup()
        {
            cboGroups.DataSource = _business.GetListGroupByKindInternId(Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id), Convert.ToInt32(((Major)cboMajors.SelectedItem).Id));
            cboGroups.DisplayMember = PropertiesConstants.Name;
            cboGroups.ValueMember = PropertiesConstants.Id;
        }

        private void LoadCondition(int kindintern, int major)
        {
            _groups = _business.GetListGroupByKindInternId(kindintern, major);
            txtCountGroups.Text = _groups.Count.ToString();
            LoadGroup();

            _lecturers = _business.GetListLecturerByMajorId(major);
            txtCountLecturers.Text = _lecturers.Count.ToString();
            LoadLecturer();

            txtNumberSubcommittee.Text = (_lecturers.Count / 2).ToString();
            txtBlance.Text = (_lecturers.Count % 2).ToString();
            LoadSubcommittee();
        }

        /// <summary>
        /// If kindinter = 3 (Graduation) then kindmark = 2, condition = 7; else kindmark = 1, condition = 0 (Intern)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            txtCountGroups.Text = txtCountLecturers.Text = string.Empty;
            var kindintern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id);
            var major = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id);
            if (kindintern != 3)  
                LoadCondition(kindintern, major);            

            else
            {
                //xoa control cu
                Controls.Clear();
                // Khoi tao control moi
                var subcommitteeStudents = new SubcommitteeStudentsControl();
                Controls.Add(subcommitteeStudents);
            }
        }
       
        private void PicShowSubcommitteeClick(object sender, EventArgs e)
        {
              // Delete old data
            _business.ClearData(Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id));

            // Insert new data
            try
            {
                var subcommittees = new List<Subcommittee>();
                var numberSubcommittee = Convert.ToInt32(txtNumberSubcommittee.Text.Trim());

                for (var i = 0; i < numberSubcommittee; i++)
                {
                    subcommittees.Add(new Subcommittee
                    {
                        Name = string.Format(DateTime.Now + "_Tiểu ban {0}", i + 1),
                        IdKindIntern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id),
                        IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                        NumberMembers = 2
                    });
                }
          
                if (subcommittees.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                _business.AddSubcommittee(subcommittees);

                dgvSubcommitteeList.DataSource = _business.GetSubcommitteeByKindInternId(((KindIntern)cboKindInterns.SelectedItem).Id, ((Major)cboMajors.SelectedItem).Id);


                LoadSubcommittee();
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }        
        }

        #region -- Subcommittee --

        private void LoadSubcommittee()
        {
            dgvSubcommitteeList.DataSource = _business.GetSubcommitteeByKindInternId(((KindIntern)cboKindInterns.SelectedItem).Id, ((Major)cboMajors.SelectedItem).Id);
            DataGridViewHelper.ShowHideColumns(dgvSubcommitteeList,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name, "NumberMembers"});
            DataGridViewHelper.ShowIsCheck(dgvSubcommitteeList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeList, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvSubcommitteeList, new[] { "IsChecked", "Name", "NumberMembers" },
                                                   new[] { "Chọn", "Tên tiểu ban", "Số lượng thành viên"});
            SubcommitteeCurrentRowChanged();
        }

        private void SubcommitteeCurrentRowChanged()
        {
            if (dgvSubcommitteeList.CurrentRow != null)
            {
                txtName.Text = dgvSubcommitteeList.CurrentRow.Cells["Name"].Value.ToString();               

                lblSubcommitteeLecturer.Text = string.Format(ConstantMessages.LblSubcommitteeLecturer, txtName.Text);

                alblSubcommitteeGroup.Text = string.Format(ConstantMessages.LblSubcommitteeGroup, txtName.Text);

                LoadSubcommitteeLecturers();
                LoadSubcommitteeGroups();
            }

            else
            {            
                ckbAllSubcommittees.Checked = false;
                dgvSubcommitteeGroup.DataSource = null;
                dgvSubcommitteeLecturer.DataSource = null;
            }
        }

        private void DgvSubcommitteeListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSubcommitteeList == null ||
               dgvSubcommitteeList.Columns[(string)typeof(Subcommittee).Properties().IsChecked] == null ||
               dgvSubcommitteeList.Columns[(string)typeof(Subcommittee).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvSubcommitteeList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvSubcommitteeList[e.ColumnIndex, e.RowIndex].Value;

            ckbAllSubcommittees.Checked = DataGridViewHelper.AllRowsIsCheck(dgvSubcommitteeList);
        }

        private void DgvSubcommitteeListCurrentCellChanged(object sender, EventArgs e)
        {
            SubcommitteeCurrentRowChanged();
        }

        private void CkbAllSubcommitteesCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeList, ckbAllSubcommittees.Checked);
        }

        private void ReloadSubcommittee(Subcommittee subcommittee)
        {
            LoadSubcommittee();
            DataGridViewHelper.SetDgvCurrentCell(dgvSubcommitteeList, subcommittee.Name);
            SubcommitteeCurrentRowChanged();
        }

        private void BtnAddSubcommitteesClick(object sender, EventArgs e)
        {
            try
            {
                var subcommittee = new Subcommittee
                {
                    Name = txtName.Text.Trim(),
                    IdKindIntern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id),
                    IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                    NumberMembers = 2
                };

                string message;

                if (_business.AddSubcommitteeValidator(subcommittee, out message))
                {
                    _business.AddSubcommittee(subcommittee);

                    ReloadSubcommittee(subcommittee);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteSubcommitteesClick(object sender, EventArgs e)
        {
            try
            {
                var subcommittees = new List<Subcommittee>();
                string message;

                for (var i = 0; i < dgvSubcommitteeList.RowCount; i++)
                {
                    if (!(bool)dgvSubcommitteeList[(string)typeof(Subcommittee).Properties().IsChecked, i].Value) continue;

                    subcommittees.Add(new Subcommittee
                    {
                        Id = (int)dgvSubcommitteeList[(string)typeof(Subcommittee).Properties().Id, i].Value,
                        Name = dgvSubcommitteeList[(string)typeof(Subcommittee).Properties().Name, i].Value.ToString(),
                        IdKindIntern = Convert.ToInt32(dgvSubcommitteeList["IdKindIntern", i].Value),
                        IdMajor = Convert.ToInt32(dgvSubcommitteeList["IdMajor", i].Value),
                        NumberMembers = 2                  
                    });
                }
                if (subcommittees.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (!_business.DeleteSubcommitteesValidator(subcommittees, out message))
                    MessageBox.Show(message);

                if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các tiểu ban đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    _business.DeleteSubcommittees(subcommittees);
                    ReloadSubcommittee(null);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnEditSubcommitteesClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvSubcommitteeList.CurrentRow != null)
                {
                    var subcommittee = new Subcommittee
                                           {
                                               Id = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells[PropertiesConstants.Id]. Value),
                                               Name = txtName.Text.Trim(),
                                               IdKindIntern =Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["IdKindIntern"].Value),
                                               IdMajor = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["IdMajor"].Value),
                                               NumberMembers = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["NumberMembers"].Value)
                                           };
                    string message;
                    if (_business.EditSubcommitteeValidator(subcommittee, out message))
                    {
                        if (!_business.EditSubcommittee(subcommittee))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadSubcommittee(subcommittee);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- Subcommittee Lecturer --

        private void LoadSubcommitteeLecturers()
              {
                  if (dgvSubcommitteeList.CurrentRow != null)
                      dgvSubcommitteeLecturer.DataSource = _business.GetLecturerBySubcommitteeId((int)dgvSubcommitteeList.CurrentRow.Cells["Id"].Value);

                  if (dgvSubcommitteeLecturer.DataSource == null)
                      return;

                  DataGridViewHelper.ShowHideColumns(dgvSubcommitteeLecturer,
                                                     new[] { PropertiesConstants.IsChecked, "LecturerName"});
                  DataGridViewHelper.ShowIsCheck(dgvSubcommitteeLecturer);
                  DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeLecturer, false);
                  DataGridViewHelper.ChangeDgvHeaderText(dgvSubcommitteeLecturer, new[] { "IsChecked", "LecturerName"},
                                                         new[] { "Chọn", "Giảng viên"});
                  SubcommitteeLecturersCurrentRowChanged();
              }             

              private void SubcommitteeLecturersCurrentRowChanged()
              {
                  if (dgvSubcommitteeLecturer.CurrentRow != null)
                      cboLecturers.Text = dgvSubcommitteeLecturer.CurrentRow.Cells["LecturerName"].Value.ToString();
                  else
                  {
                      cboLecturers.SelectedIndex = -1;
                      ckbSubcommitteeLecturer.Checked = false;
                  }
              }

              private void DgvSubcommitteeLecturerCellContentClick(object sender, DataGridViewCellEventArgs e)
              {
                  if (dgvSubcommitteeLecturer == null ||
                     dgvSubcommitteeLecturer.Columns[(string)typeof(SubcommitteeLecturer).Properties().IsChecked] == null ||
                     dgvSubcommitteeLecturer.Columns[(string)typeof(SubcommitteeLecturer).Properties().IsChecked].Index != e.ColumnIndex)
                      return;

                  dgvSubcommitteeLecturer[e.ColumnIndex, e.RowIndex].Value =
                      !(bool)dgvSubcommitteeLecturer[e.ColumnIndex, e.RowIndex].Value;

                  ckbSubcommitteeLecturer.Checked = DataGridViewHelper.AllRowsIsCheck(dgvSubcommitteeLecturer);
              }

              private void DgvSubcommitteeLecturerCurrentCellChanged(object sender, EventArgs e)
              {
                  SubcommitteeLecturersCurrentRowChanged();
              }

              private void CkbSubcommitteeLecturerCheckedChanged(object sender, EventArgs e)
              {
                  DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeLecturer, ckbSubcommitteeLecturer.Checked);
              }

              private void ReloadSubcommitteeLecturer(SubcommitteeLecturer subcommittee)
              {
                  LoadSubcommitteeLecturers();
                  DataGridViewHelper.SetDgvCurrentCell(dgvSubcommitteeLecturer, subcommittee.LecturerName);
                  SubcommitteeCurrentRowChanged();
              }

              private void BtnAddSubcommitteeLecturerClick(object sender, EventArgs e)
              {
                  try
                  {
                      if (dgvSubcommitteeList.CurrentRow != null && dgvSubcommitteeLecturer.RowCount < 2)
                      {
                          var subcommittee = new SubcommitteeLecturer
                          {
                              IdSubcommittee = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["Id"].Value),
                              IdLecturer = Convert.ToInt32(((Lecturer)cboLecturers.SelectedItem).Id)
                          };

                          string message;

                          if (_business.AddSubcommitteeLecturerValidator(subcommittee, out message))
                          {
                              _business.AddSubcommitteeLecturer(subcommittee);

                              ReloadSubcommitteeLecturer(subcommittee);
                          }
                          else
                              MessageBox.Show(message);
                      }
                  }
                  catch (Exception ex)
                  {
                      Logger.Write(null, ex);
                  }
              }

              private void BtnDeleteSubcommitteeLecturersClick(object sender, EventArgs e)
              {
                  try
                  {
                      var subcommittees = new List<SubcommitteeLecturer>();
                      string message;
                      for (var i = 0; i < dgvSubcommitteeLecturer.RowCount; i++)
                      {
                          if (!(bool)dgvSubcommitteeLecturer[(string)typeof(SubcommitteeLecturer).Properties().IsChecked, i].Value) continue;

                          subcommittees.Add(new SubcommitteeLecturer
                          {
                              Id = (int)dgvSubcommitteeLecturer[(string)typeof(SubcommitteeLecturer).Properties().Id, i].Value,
                              IdSubcommittee = Convert.ToInt32(dgvSubcommitteeLecturer["IdSubcommittee", i].Value),
                              IdLecturer = Convert.ToInt32(dgvSubcommitteeLecturer["IdLecturer", i].Value),
                          });
                      }
                      if (subcommittees.Count < 1)
                      {
                          MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                          return;
                      }

                      if (_business.DeleteSubcommitteeLecturerValidator(subcommittees, out message))
                      {
                          if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các thành viên tiểu ban đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                          {
                              _business.DeleteSubcommitteeLecturer(subcommittees);
                              ReloadSubcommitteeLecturer(null);
                          }
                      }
                      else MessageBox.Show(message);
                  }
                  catch (Exception ex)
                  {
                      Logger.Write(null, ex);
                  }
              }             
         #endregion

        #region -- Subcommittee Groups --

              private void LoadSubcommitteeGroups()
              {
                  if (dgvSubcommitteeList.CurrentRow != null)
                      dgvSubcommitteeGroup.DataSource = _business.GetGroupBySubcommitteeId((int)dgvSubcommitteeList.CurrentRow.Cells["Id"].Value);

                  if (dgvSubcommitteeGroup.DataSource == null)
                      return;

                  DataGridViewHelper.ShowHideColumns(dgvSubcommitteeGroup,
                                                     new[] { PropertiesConstants.IsChecked, "GroupName" });
                  DataGridViewHelper.ShowIsCheck(dgvSubcommitteeGroup);
                  DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeGroup, false);
                  DataGridViewHelper.ChangeDgvHeaderText(dgvSubcommitteeGroup, new[] { "IsChecked", "GroupName" },
                                                         new[] { "Chọn", "Nhóm" });
                  SubcommitteeGroupsCurrentRowChanged();
              }            

              private void SubcommitteeGroupsCurrentRowChanged()
              {
                  if (dgvSubcommitteeGroup.CurrentRow != null)
                      cboGroups.Text = dgvSubcommitteeGroup.CurrentRow.Cells["GroupName"].Value.ToString();
                  else
                  {
                      cboGroups.SelectedIndex = -1;
                      ckbSubcommitteeGroup.Checked = false;
                  }
              }

              private void DgvSubcommitteeGroupCellContentClick(object sender, DataGridViewCellEventArgs e)
              {
                  if (dgvSubcommitteeGroup == null ||
                     dgvSubcommitteeGroup.Columns[(string)typeof(SubcommitteeGroup).Properties().IsChecked] == null ||
                     dgvSubcommitteeGroup.Columns[(string)typeof(SubcommitteeGroup).Properties().IsChecked].Index != e.ColumnIndex)
                      return;

                  dgvSubcommitteeGroup[e.ColumnIndex, e.RowIndex].Value =
                      !(bool)dgvSubcommitteeGroup[e.ColumnIndex, e.RowIndex].Value;

                  ckbSubcommitteeGroup.Checked = DataGridViewHelper.AllRowsIsCheck(dgvSubcommitteeGroup);
              }

              private void DgvSubcommitteeGroupCurrentCellChanged(object sender, EventArgs e)
              {
                  SubcommitteeGroupsCurrentRowChanged();
              }

              private void CkbSubcommitteeGroupCheckedChanged(object sender, EventArgs e)
              {
                  DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeGroup, ckbSubcommitteeGroup.Checked);
              }

              private void ReloadSubcommitteeGroup(SubcommitteeGroup subcommittee)
              {
                  LoadSubcommitteeGroups();
                  DataGridViewHelper.SetDgvCurrentCell(dgvSubcommitteeGroup, subcommittee.GroupName);
                  SubcommitteeCurrentRowChanged();
              }

              private void BtnAddSubcommitteeGroupClick(object sender, EventArgs e)
              {
                  try
                  {
                      if (dgvSubcommitteeList.CurrentRow != null)
                      {
                          var subcommittee = new SubcommitteeGroup
                          {
                              IdSubcommittee = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["Id"].Value),
                              IdGroup = Convert.ToInt32(((Group)cboGroups.SelectedItem).Id)
                          };
                          string message;
                          if (_business.AddSubcommitteeGroupValidator(subcommittee, out message))
                          {
                              _business.AddSubcommitteeGroup(subcommittee);
                              ReloadSubcommitteeGroup(subcommittee);
                          }
                          else
                              MessageBox.Show(message);
                      }
                  }
                  catch (Exception ex)
                  {
                      Logger.Write(null, ex);
                  }
              }

              private void BtnDeleteSubcommitteeGroupsClick(object sender, EventArgs e)
              {
                  try
                  {
                      var subcommittees = new List<SubcommitteeGroup>();
                      string message;

                      for (var i = 0; i < dgvSubcommitteeGroup.RowCount; i++)
                      {
                          if (!(bool)dgvSubcommitteeGroup[(string)typeof(SubcommitteeGroup).Properties().IsChecked, i].Value) continue;

                          subcommittees.Add(new SubcommitteeGroup
                          {
                              Id = (int)dgvSubcommitteeGroup[(string)typeof(SubcommitteeGroup).Properties().Id, i].Value,
                              IdSubcommittee = Convert.ToInt32(dgvSubcommitteeGroup["IdSubcommittee", i].Value),
                              IdGroup = Convert.ToInt32(dgvSubcommitteeGroup["IdGroup", i].Value)
                          });
                      }
                      if (subcommittees.Count < 1)
                      {
                          MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                          return;
                      }

                      if (_business.DeleteSubcommitteeGroupValidator(subcommittees, out message))
                      {
                          if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các nhóm tiểu ban đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                          {
                              _business.DeleteSubcommitteeGroup(subcommittees);
                              ReloadSubcommitteeGroup(null);
                          }
                      }
                      else MessageBox.Show(message);
                  }
                  catch (Exception ex)
                  {
                      Logger.Write(null, ex);
                  }
              }            
              #endregion
        }
    }
